import { _decorator, clamp, Component, Vec2, Vec3 } from 'cc';
import { aa } from '../frame/FrameCore';
const { ccclass, property } = _decorator;

const pos = new Vec3();

@ccclass('BezierMove')
export class BezierMove extends Component {
    @property duration = 1;
    @property multiplier = 3;
    @property offset = new Vec2(200,500);
    @property autoClose = false;
    private _time = 0;
    private _end = true;
    private startPos = new Vec3();
    private midPos = new Vec3();
    private endPos = new Vec3();

    init(start:Vec3,end:Vec3) {
        const p0 = this.startPos;
        const p1 = this.midPos;
        const p2 = this.endPos;
        Vec3.copy(p0,start);
        Vec3.copy(p2,end);
        const dir = aa.utils.getOne();
        p1.x = (p2.x+p0.x)*0.5+(Math.random()+1)*dir*this.offset.x;
        p1.x = clamp(p1.x,-690,690);
        p1.y = Math.max(p0.y,p2.y)+this.offset.y*(1+Math.random());
        p1.z = (p2.z+p0.z)*0.5;
        this._time = 0;
        this._end = false;
    }

    update(deltaTime: number) {
        if(this._end) return;
        this._time += deltaTime/this.duration;
        if(this._time>1){
            this._time = 1;
            this._end = true;
            if(this.autoClose){
                this.node.active = false;
            }
        }
        const p0 = this.startPos;
        const p1 = this.midPos;
        const p2 = this.endPos;
        const t = this._time;
        const t1 = ((1 - t) * (1 - t));
        const t2 = (this.multiplier * (1 - t) * t);
        const t3 = (t*t);
        pos.x = p0.x*t1+p1.x*t2+p2.x*t3;
        pos.y = p0.y*t1+p1.y*t2+p2.y*t3;
        /* enabled in 3d game:P */
        // pos.z = p0.z*t1+p1.z*t2+p2.z*t3;
        this.node.worldPosition = pos;
    }
}

